<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户姓名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户邮箱" prop="userEmail">
        <el-input
          v-model="queryParams.userEmail"
          placeholder="请输入用户邮箱"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="测试状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择测试状态" clearable>
          <el-option label="进行中" value="0" />
          <el-option label="已完成" value="1" />
          <el-option label="已放弃" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="测试时间">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['mbti:testRecord:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['mbti:testRecord:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['mbti:testRecord:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="DataAnalysis"
          @click="showStatistics = true"
          v-hasPermi="['mbti:testRecord:statistics']"
        >统计</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="testRecordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="记录ID" align="center" prop="recordId" width="80" />
      <el-table-column label="用户信息" align="center" width="200">
        <template #default="scope">
          <div>{{ scope.row.userName || '匿名用户' }}</div>
          <div v-if="scope.row.userEmail" class="text-muted">{{ scope.row.userEmail }}</div>
        </template>
      </el-table-column>
      <el-table-column label="测试类型" align="center" prop="testTypeName" width="120" />
      <el-table-column label="测试状态" align="center" width="100">
        <template #default="scope">
          <dict-tag :options="testStatusOptions" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="160">
        <template #default="scope">
          <span v-if="scope.row.endTime">{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="用时" align="center" width="80">
        <template #default="scope">
          <span v-if="scope.row.duration">{{ formatDuration(scope.row.duration) }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="IP地址" align="center" prop="ipAddress" width="120" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['mbti:testRecord:detail']">详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['mbti:testRecord:edit']">修改</el-button>
          <el-button link type="warning" icon="RefreshRight" @click="handleRecalculate(scope.row)" v-hasPermi="['mbti:testRecord:edit']" v-if="scope.row.status === '1'">重算</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['mbti:testRecord:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 修改测试记录对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="testRecordRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="用户姓名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户姓名" maxlength="100" />
        </el-form-item>
        <el-form-item label="用户邮箱" prop="userEmail">
          <el-input v-model="form.userEmail" placeholder="请输入用户邮箱" maxlength="100" />
        </el-form-item>
        <el-form-item label="测试状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">进行中</el-radio>
            <el-radio label="1">已完成</el-radio>
            <el-radio label="2">已放弃</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 测试记录详情对话框 -->
    <el-dialog title="测试记录详情" v-model="detailOpen" width="1200px" append-to-body>
      <el-descriptions :column="2" border class="mb-4">
        <el-descriptions-item label="记录ID">{{ detailForm.record?.recordId }}</el-descriptions-item>
        <el-descriptions-item label="测试类型">{{ detailForm.record?.testTypeName }}</el-descriptions-item>
        <el-descriptions-item label="用户姓名">{{ detailForm.record?.userName || '匿名用户' }}</el-descriptions-item>
        <el-descriptions-item label="用户邮箱">{{ detailForm.record?.userEmail || '-' }}</el-descriptions-item>
        <el-descriptions-item label="测试状态">
          <dict-tag :options="testStatusOptions" :value="detailForm.record?.status"/>
        </el-descriptions-item>
        <el-descriptions-item label="IP地址">{{ detailForm.record?.ipAddress || '-' }}</el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ parseTime(detailForm.record?.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ detailForm.record?.endTime ? parseTime(detailForm.record.endTime, '{y}-{m}-{d} {h}:{i}:{s}') : '-' }}</el-descriptions-item>
      </el-descriptions>

      <!-- 测试结果 -->
      <div v-if="detailForm.result" class="mt-4">
        <h3>测试结果</h3>
        <el-card>
          <div class="result-content">
            <div class="personality-type">
              <h2>{{ detailForm.result.personalityType }}</h2>
              <div class="scores">
                <div class="score-item">
                  <span>E/I: </span>
                  <el-progress :percentage="getScorePercentage(detailForm.result.eScore, detailForm.result.iScore)" :color="getProgressColor('EI')" />
                  <span>{{ detailForm.result.eScore }}/{{ detailForm.result.iScore }}</span>
                </div>
                <div class="score-item">
                  <span>S/N: </span>
                  <el-progress :percentage="getScorePercentage(detailForm.result.sScore, detailForm.result.nScore)" :color="getProgressColor('SN')" />
                  <span>{{ detailForm.result.sScore }}/{{ detailForm.result.nScore }}</span>
                </div>
                <div class="score-item">
                  <span>T/F: </span>
                  <el-progress :percentage="getScorePercentage(detailForm.result.tScore, detailForm.result.fScore)" :color="getProgressColor('TF')" />
                  <span>{{ detailForm.result.tScore }}/{{ detailForm.result.fScore }}</span>
                </div>
                <div class="score-item">
                  <span>J/P: </span>
                  <el-progress :percentage="getScorePercentage(detailForm.result.jScore, detailForm.result.pScore)" :color="getProgressColor('JP')" />
                  <span>{{ detailForm.result.jScore }}/{{ detailForm.result.pScore }}</span>
                </div>
              </div>
            </div>
            <div v-if="detailForm.result.resultDescription" class="result-description">
              <h4>结果描述</h4>
              <p>{{ detailForm.result.resultDescription }}</p>
            </div>
          </div>
        </el-card>
      </div>
    </el-dialog>

    <!-- 统计信息对话框 -->
    <el-dialog title="测试记录统计" v-model="showStatistics" width="1000px" append-to-body>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card>
            <el-statistic title="总测试数" :value="statisticsData.totalTests" />
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card>
            <el-statistic title="已完成" :value="statisticsData.completedTests" />
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card>
            <el-statistic title="完成率" :value="statisticsData.completionRate" suffix="%" :precision="2" />
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card>
            <el-statistic title="平均用时" :value="Math.round(statisticsData.averageDuration / 60)" suffix="分钟" />
          </el-card>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script setup name="TestRecord">
import { listTestRecord, getTestRecord, delTestRecord, updateTestRecord, getTestRecordDetail, batchUpdateStatus, getTestRecordStatistics, recalculateResult } from "@/api/mbti/testRecord";

const { proxy } = getCurrentInstance();
const { parseTime } = proxy.useDict();

const testRecordList = ref([]);
const open = ref(false);
const detailOpen = ref(false);
const showStatistics = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);

const testStatusOptions = ref([
  { label: "进行中", value: "0" },
  { label: "已完成", value: "1" },
  { label: "已放弃", value: "2" }
]);

const data = reactive({
  form: {},
  detailForm: {},
  statisticsData: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: null,
    userEmail: null,
    status: null,
    startDate: null,
    endDate: null
  },
  rules: {
    userName: [
      { required: true, message: "用户姓名不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, detailForm, statisticsData, rules } = toRefs(data);

/** 查询测试记录列表 */
function getList() {
  loading.value = true;
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.value.startDate = dateRange.value[0];
    queryParams.value.endDate = dateRange.value[1];
  } else {
    queryParams.value.startDate = null;
    queryParams.value.endDate = null;
  }

  listTestRecord(queryParams.value).then(response => {
    testRecordList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    recordId: null,
    userName: null,
    userEmail: null,
    status: null
  };
  proxy.resetForm("testRecordRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.recordId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _recordId = row.recordId || ids.value
  getTestRecord(_recordId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改测试记录";
  });
}

/** 查看详情 */
function handleView(row) {
  getTestRecordDetail(row.recordId).then(response => {
    detailForm.value = response.data;
    detailOpen.value = true;
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["testRecordRef"].validate(valid => {
    if (valid) {
      updateTestRecord(form.value).then(response => {
        proxy.$modal.msgSuccess("修改成功");
        open.value = false;
        getList();
      });
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _recordIds = row.recordId || ids.value;
  proxy.$modal.confirm('是否确认删除测试记录编号为"' + _recordIds + '"的数据项？').then(function() {
    return delTestRecord(_recordIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 重新计算结果 */
function handleRecalculate(row) {
  proxy.$modal.confirm('是否确认重新计算该测试记录的结果？').then(function() {
    return recalculateResult(row.recordId);
  }).then(() => {
    proxy.$modal.msgSuccess("重新计算成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('mbti/testRecord/export', {
    ...queryParams.value
  }, `testRecord_${new Date().getTime()}.xlsx`)
}

/** 格式化时长 */
function formatDuration(seconds) {
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  return `${minutes}分${remainingSeconds}秒`;
}

/** 计算分数百分比 */
function getScorePercentage(score1, score2) {
  const total = score1 + score2;
  return total > 0 ? Math.round((score1 / total) * 100) : 50;
}

/** 获取进度条颜色 */
function getProgressColor(dimension) {
  const colors = {
    'EI': '#409EFF',
    'SN': '#67C23A',
    'TF': '#E6A23C',
    'JP': '#F56C6C'
  };
  return colors[dimension] || '#409EFF';
}

/** 获取统计数据 */
watch(showStatistics, (val) => {
  if (val) {
    getTestRecordStatistics().then(response => {
      statisticsData.value = response.data;
    });
  }
});

getList();
</script>

<style scoped>
.result-content {
  padding: 20px;
}

.personality-type h2 {
  text-align: center;
  color: #409EFF;
  margin-bottom: 20px;
}

.scores .score-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.scores .score-item span:first-child {
  width: 50px;
  font-weight: bold;
}

.scores .score-item .el-progress {
  flex: 1;
  margin: 0 15px;
}

.result-description {
  margin-top: 20px;
}

.result-description h4 {
  color: #606266;
  margin-bottom: 10px;
}

.text-muted {
  color: #909399;
  font-size: 12px;
}
</style>
